package com.vcc.web.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.mybatisflex.core.paginate.Page;
import com.vcc.core.annotations.CurrentROStatus;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.model.file.walletDetail.WalletDetailFilePojo;
import com.vcc.core.util.DateUtil;
import com.vcc.core.util.FileUtil;
import com.vcc.core.util.RegexUtil;
import com.vcc.data.entity.Currency;
import com.vcc.data.entity.Role;
import com.vcc.data.entity.User;
import com.vcc.data.entity.WalletDetail;
import com.vcc.web.core.util.UserUtil;
import com.vcc.service.client.vo.walletDetail.WalletDetailVo;
import com.vcc.service.service.CurrencyService;
import com.vcc.service.service.UserService;
import com.vcc.service.service.WalletDetailService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("walletDetail")
public class WalletDetailController {


    @Autowired
    private UserService userService;
    @Autowired
    private WalletDetailService walletDetailService;
    @Autowired
    private CurrencyService currencyService;


    @RestPack
    @GetMapping("paging")
    @SaCheckPermission("wallet:detail:view")
    public Page<WalletDetailVo> paging(
            Page<WalletDetail> pageable,
            Long targetUserId,
            String orderId,
            Integer useFlag,
            String startDate,
            String endDate,
            String cardNumber,
            String remark
    ) {
        User user = UserUtil.get();
        Long parentId = user.getParentId();
        Role role = UserUtil.getRole();
        Page<WalletDetail> paging = walletDetailService.paging(
                pageable,
                role,
                role.getHasAllData() && parentId != null && parentId != 0 ? parentId : user.getId(),
                targetUserId,
                cardNumber,
                useFlag,
                startDate,
                endDate,
                remark,
                orderId);
        List<Currency> list = currencyService.list();
        return paging.map(it -> {
            String account = it.getUserId() == null || it.getUserId() == 0L ? "" : userService.getAccountById(it.getUserId());
            String dealerAccount = it.getOperationUserId() == null || it.getOperationUserId() == 0L ? "" : userService.getAccountById(it.getOperationUserId());
            Currency currency = list.stream().filter(cur -> cur.getId().equals(it.getCurrencyId())).findAny().orElse(null);
            return new WalletDetailVo(it, account, dealerAccount, currency);
        });
    }


    @SaCheckPermission("wallet:detail:derive")
    @GetMapping("derive")
    @SaCheckLogin
    public void derive(
            @CurrentROStatus Boolean roStatus,
            Long targetUserId,
            Integer useFlag,
            String startDate,
            String endDate,
            String cardNumber,
            String remark,
            String orderId,
            HttpServletResponse response
    ) {
        User user = UserUtil.get();
        Long parentId = user.getParentId();
        Role role = UserUtil.getRole();
        if (RegexUtil.checkStringIsNull(startDate)) {
            response.setStatus(500);
            throw new ProgramException("请选择开始时间");
        }
        if (RegexUtil.checkStringIsNull(endDate)) {
            response.setStatus(500);
            throw new ProgramException("请选择结束时间");
        }
        Long pages = 1L;
        Page<WalletDetail> paging;
        SXSSFWorkbook sxssfWorkbook = FileUtil.createWalletDetailTitle(10000);
        List<Currency> currencyList = currencyService.list();
        do {
            paging = walletDetailService.paging(
                    Page.of(pages++, 1000),
                    role,
                    role.getHasAllData() && parentId != null && parentId != 0 ? parentId : user.getId(),
                    targetUserId,
                    cardNumber,
                    useFlag,
                    startDate,
                    endDate,
                    remark,
                    orderId);
            List<WalletDetailFilePojo> list = paging.getRecords().stream().map(it -> {
                String account = it.getUserId() == null || it.getUserId() == 0L ? "" : userService.getAccountById(it.getUserId());
                Currency currency = currencyList.stream().filter(cur -> cur.getId().equals(it.getCurrencyId())).findAny().orElse(null);
                return new WalletDetailFilePojo(
                        it.getOrderId(),
                        it.getCardNumber(),
                        it.getUseFlag(),
                        it.getRemark(),
                        it.getAmount(),
                        it.getWalletAmount(), currency == null ? "" : currency.getName(),
                        account,
                        "",
                        DateUtil.format(it.getRequestDate()),
                        it.getHasTransferIn());
            }).collect(Collectors.toList());
            FileUtil.deriveWalletDetailData(sxssfWorkbook, list, paging.getPageNumber(), paging.getPageSize(), roStatus);
        } while (!(pages).equals(paging.getTotalPage() + 1));
        String fileName = System.currentTimeMillis() + "账单明细.xlsx";
        FileUtil.downXlsxFile(response, sxssfWorkbook, fileName);
    }

}
